<!-- 能源绩效 -->
<template>
  <div v-loading="tableLoading" class="energy-performance-wrap">
    <div class="lf-wrap">
      <div class="black mg-bt-16">
        <px-form ref="formRef" :model="queryParams" :inline="true" class="search-form">
          <px-form-item label="时间范围" prop="dateRange">
            <px-date-picker
              v-model="queryParams.dateRange"
              type="monthrange"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              value-format="YYYY-MM"
            />
          </px-form-item>
          <div class="search-form-btn">
            <px-button type="primary" @click="handleQuery">查询</px-button>
            <px-button @click="resetQuery">重置</px-button>
          </div>
        </px-form>
        <px-table height="300px" :data="tableData" size="small" border class="table-content common-table">
          <px-table-column type="index" label="序号" fixed width="55" align="center" />
          <px-table-column prop="month" label="时间" min-width="120" show-overflow-tooltip />
          <px-table-column prop="unitProduction" label="单位产品综合能耗tec/pcs" min-width="120" show-overflow-tooltip />
          <px-table-column prop="scoalNum" label="单位产品耗电kWh/pcs" min-width="120" show-overflow-tooltip />
          <px-table-column prop="scoalNum" label="单位产品耗自来水m³/pcs" min-width="120" show-overflow-tooltip />
          <px-table-column prop="scoalNum" label="单位产品耗再生水m³/pcs" min-width="120" show-overflow-tooltip />
          <px-table-column prop="scoalNum" label="单位产品耗蒸汽/热水GJ/pcs" min-width="120" show-overflow-tooltip />
          <px-table-column prop="scoalNum" label="单位产品耗天然气m³/pcs" min-width="120" show-overflow-tooltip />
          <px-table-column prop="scoalNum" label="单位产品大宗气m³/pcs" min-width="120" show-overflow-tooltip />
        </px-table>
      </div>
    </div>
    <div class="rt-wrap">
      <modelTitle :title="'单位产品综合能耗'" />
      <div ref="trendChartRef" class="chart" style="width: 100%; height: 400px" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from "vue";
import * as echarts from "echarts";
import { getViewPerformanceAPI, getLineDirectrixAPI } from "@/api/energy/performance";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import dayjs from "dayjs";

defineOptions({
  name: "ALL_ENERGY_PERFORMANCE_INDEX"
});

const formRef = ref();
const trendChartRef = ref(null);

const state = reactive({
  queryParams: {
    dateRange: ""
  },
  tableData: [],
  tableLoading: true
});
const { queryParams, tableLoading, tableData } = toRefs(state);

onMounted(() => {
  initQuery();
  getData();
});

// 获取开始时间和结束时间还有厂区
const getParams = () => {
  try {
    let startDate = "";
    let endDate = "";
    let dateRange = state.queryParams.dateRange;
    startDate = dateRange[0] ? dateRange[0] + "-01 00:00:00" : "";
    endDate = dateRange[1] ? getLastDayOfMonth(dateRange[1]) + " 23:59:59" : "";
    return {
      startDate,
      endDate
    };
  } catch (error) {}
};

// 获取表格和折线图数据
const getViewPerformanceData = async () => {
  // try {
  //   const { factory, startDate, endDate } = getParams();
  //   let params = {
  //     dimension: "MONTH",
  //     startDate: startDate,
  //     endDate: endDate,
  //     factory: factory,
  //     sysId: ""
  //   };
  //   const res = await getViewPerformanceAPI(params);
  //   let tableData = res?.table || [];
  //   tableData.forEach(item => {
  //     item.yoy = item.yoy === null ? "-" : item.yoy + "%";
  //     item.mom = item.mom === null ? "-" : item.mom + "%";
  //   });
  //   state.tableData = tableData;
  //   let trend = res?.trend || {};
  //   initChart(trend);
  // } catch (error) {
  //   console.log(error);
  // }
  try {
    const { startDate, endDate } = getParams();
    let params = {
      dimension: "MONTH",
      startDate: startDate,
      endDate: endDate,
      sysId: ""
    };
    return await getViewPerformanceAPI(params);
  } catch (error) {}
};

// 获取能源绩效基准线
const getLineDirectrixData = async () => {
  // try {
  //   const { factory, startDate, endDate } = getParams();
  //   let params = {
  //     dimension: "MONTH", // MONTH-月 为空时默认 MONTH
  //     factory: factory,
  //     startDate: startDate,
  //     endDate: endDate
  //   };
  //   const res = await getLineDirectrixAPI(params);
  //   if (res?.yaxis?.value?.length) {
  //     state.LineData = res?.yaxis?.value;
  //   } else {
  //     state.LineData = [];
  //   }
  // } catch (error) {}
  try {
    const { startDate, endDate } = getParams();
    let params = {
      dimension: "MONTH", // MONTH-月 为空时默认 MONTH
      startDate: startDate,
      endDate: endDate,
      energyType: 1
    };
    return await getLineDirectrixAPI(params);
  } catch (error) {}
};

// 获取数据
const getData = async () => {
  try {
    state.tableLoading = true;
    const [res1, res2] = await Promise.all([getViewPerformanceData(), getLineDirectrixData()]);
    // 表格数据处理
    let tableData = res1?.table || [];
    tableData.forEach(item => {
      item.yoy = item.yoy === null ? "-" : item.yoy + "%";
      item.mom = item.mom === null ? "-" : item.mom + "%";
    });
    state.tableData = tableData;
    // 折线图的数据
    let trend = res1?.trend || {};
    // 折线图的基线
    let baseLine = res2?.yaxis?.value || [];
    // 画图
    initChart(trend, baseLine);
  } catch (error) {
    console.log(error);
  } finally {
    state.tableLoading = false;
  }
};
// 根据YYYY-MM格式的日期，获取对应的月份的最后一天
const getLastDayOfMonth = yearMonth => {
  return dayjs(yearMonth).endOf("month").format("YYYY-MM-DD") || yearMonth;
};

// 默认查询条件
const initQuery = () => {
  state.queryParams.dateRange = [dayjs().subtract(12, "month").format("YYYY-MM"), dayjs().subtract(1, "month").format("YYYY-MM")];
};
// 初始化折线图
const initChart = (args1, args2) => {
  let name = args1?.yaxis?.[0]?.name || "单位产品综合能耗";
  let xAxisAry = args1?.xaxis || [];
  let seriesData = [
    {
      data: args1?.yaxis?.[0]?.value || [],
      type: "line"
    },
    {
      data: args2,
      type: "line"
    }
  ];

  const options = {
    tooltip: {
      trigger: "axis"
    },
    xAxis: {
      data: xAxisAry
    },
    yAxis: {
      name: "单位：tce/pcs",
      type: "value"
    },
    series: seriesData
  };
  let myChart = echarts.init(trendChartRef.value);
  myChart.clear();
  myChart.setOption(options);
};

// 查询
const handleQuery = () => {
  getData();
};
// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  initQuery();
  handleQuery();
};
</script>
<style lang="scss" scoped>
.energy-performance-wrap {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.search-form {
  display: flex;
  align-items: center;

  .search-form-btn {
    margin-bottom: 16px;
  }
}

.mg-bt-16 {
  margin-bottom: 16px;
}

.lf-wrap {
  display: flex;
  flex: 1;
  flex-direction: column;

  .black {
    position: relative;
    display: flex;
    flex: 1;
    flex-direction: column;
    padding: 16px 24px;
    background: #fff;
    border-radius: 4px;

    .table-wrap {
      flex: 1;
      margin-top: 16px;
    }
  }
}

.rt-wrap {
  position: relative;
  display: flex;
  flex: 1;
  flex-direction: column;
  padding: 16px 24px;
  background: #fff;
  border-radius: 4px;

  .chart {
    flex: 1;
    margin-top: 26px;
  }
}

.btn {
  position: absolute;
  top: 16px;
  right: 24px;
}
</style>
